import { ref, onMounted, onBeforeUnmount } from 'vue';
const useWebSocket = (url:string) => {
    const socket:any = ref(null);
    const connect = () => {
        socket.value = new WebSocket(url);

        socket.value.addEventListener('open', () => {
            console.log('WebSocket连接已打开');
        });

        socket.value.addEventListener('message', (event:any) => {
            console.log('收到消息:', event.data);
        });

        socket.value.addEventListener('close', () => {
            console.log('WebSocket连接已关闭');
            // 可以在此处理连接关闭的逻辑，例如尝试重新连接
        });
    };

    const sendMessage = (message:string) => {
        if (socket.value && socket.value.readyState === WebSocket.OPEN) {
            socket.value.send(message);
        }
    };

    onMounted(() => {
        connect();
    });

    onBeforeUnmount(() => {
        if (socket.value) {
            socket.value.close();
        }
    });

    return {
        socket,
        sendMessage,
    };
};

export default useWebSocket;